package com.example.mytestdemo.customviewbook

import android.graphics.Camera
import android.util.Log
import android.view.animation.Animation
import android.view.animation.Transformation

/**
 * @author tgw
 * @date 2023/2/3
 * @describe
 */
class Rotation3dAnimation : Animation {
    private var mFromDegrees: Float
    private var mToDegrees: Float
    private var mCenterX: Float = 0.0f
    private var mCenterY: Float = 0.0f
    private lateinit var mCamera: Camera

    //相机固定的距离是576
    private  var mDepth: Float= 500.0f
    //没有反转代表从0-180，角度旋转
    private var isReversal = false

    constructor(mFromDegrees: Float, mToDegrees: Float, isReversal:Boolean) {
        this.mFromDegrees = mFromDegrees
        this.mToDegrees = mToDegrees
        this.isReversal = isReversal
    }

    override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) {
        super.initialize(width, height, parentWidth, parentHeight)
        mCenterX = (width / 2).toFloat()
        mCenterY = (height / 2).toFloat()
        mCamera = Camera()
    }


    override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
        var degrees = mFromDegrees + (mToDegrees - mFromDegrees) * interpolatedTime
        Log.d("TAG", "applyTransformation mFromDegrees: ${mFromDegrees}--mToDegrees:$mToDegrees----interpolatedTime:$interpolatedTime")
        Log.d("TAG", "applyTransformation degrees: $degrees")

        mCamera.save()
        var z = 0f
        //从当前的效果图可以看出，随着旋转角度的增加，倾斜之后的图像会变大，在旋转角度达到90°时图像最大。
        //同样地，要解决这个问题，就得随着图像变大，将View与Camera的距离增大，这样View就会变小。所以，这个View与Camera的距离变化过程就形成了上面的曲线。
        if (!isReversal){
            z = mDepth*interpolatedTime
            mCamera.translate(0f,0f,z)
        }else  {
            z = mDepth*(1f-interpolatedTime)
            mCamera.translate(0f,0f,z)
        }
        Log.d("TAG", "applyTransformation ---z:$z ")
        var matrix=t?.matrix
        mCamera.rotateY(degrees)
        mCamera.getMatrix(matrix)
        mCamera.restore()

        matrix?.preTranslate(-mCenterX,-mCenterY)
        matrix?.postTranslate(mCenterX,mCenterY)

        super.applyTransformation(interpolatedTime, t)
    }
}